import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { isEmpty } from 'lodash';
import * as bcrypt from 'bcryptjs';
import { ApiException } from 'src/core/exceptions/api.exception';
import Company from 'src/entities/company.entity';
import Student from 'src/entities/student.entity';
import User from 'src/entities/user.entity';
import { Repository } from 'typeorm';
import { UpdateUserDto } from './user.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private userRepository: Repository<User>,
    @InjectRepository(Student) private studentRepository: Repository<Student>,
    @InjectRepository(Company) private companyRepository: Repository<Company>,
  ) {}

  // 查询用户信息
  async findOne(id: string) {
    const user = await this.userRepository.findOne({
      where: { id },
      select: ['id', 'nickname', 'avatar', 'role'],
    });

    if (isEmpty(user)) {
      throw new ApiException(10005);
    }

    if (user.role === 'student') {
      const student = await this.studentRepository.findOne({ where: { userId: id } });
      return { ...user, studentId: student.id };
    }

    const company = await this.companyRepository.findOne({ where: { userId: id } });
    return { ...user, companyId: company.id };
  }

  // 更新用户信息
  async update(userInfo: UpdateUserDto) {
    const { id, nickname, avatar } = userInfo;
    await this.userRepository.update(id, { nickname, avatar });
  }

  // 更新为学生角色
  // async switchRoleStudent(id: string) {
  //   await this.userRepository.update(id, { role: 'student' });
  // }

  // 切换为公司角色
  // async updateRoleCompany(updateRoleCompanyDto: UpdateRoleCompanyDto) {
  //   const { username, password } = updateRoleCompanyDto;

  //   const user = await this.userRepository.findOne({ where: { username } });
  //   if (isEmpty(user)) {
  //     throw new ApiException(10007);
  //   } else if (!bcrypt.compareSync(password, user.password)) {
  //     throw new ApiException(10007);
  //   }

  //   await this.userRepository.update({ id: user.id }, { role: 'company' });
  // }
}
